import json
import requests


class MY_MaaS_2025_HTTP_CAN_USE:
    API_URL = "http://maas-api.cn-huabei-1.xf-yun.com/v1/chat/completions"
    API_KEY = "sk-AvPi70UV1yVyVnkF8967D01f9b3f40E0A48bBe94AbCcA3Cc"

    def invoke(self, prompt_info):
        try:
            invoke_request = self.invoke_request(prompt_info)
            response = json.loads(invoke_request)
            choices = response["choices"][0]
            return choices["message"]["content"]
        except Exception as e:
            print(e)
            return ""

    def invoke_request(self, prompt_info):
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.API_KEY}",
            "lora_id": "1945679103809183744"
        }

        data = self._build_request_body(prompt_info)

        response = requests.post(
            self.API_URL,
            headers=headers,
            json=data,
            timeout=(500, 1800)  # connect timeout, read timeout in seconds
        )

        if not response.ok:
            raise Exception(f"Unexpected code {response.status_code}")

        return response.text

    def _build_request_body(self, prompt_info, model=""):
        prompts = []

        message = {
            "role": "user",
            "content": prompt_info
        }
        prompts.append(message)

        request = {
            "model": "xdeepseekr1qwen32b",
            "stream": False,
            "temperature": 0.5,
            "top_k": 4,
            "max_tokens": 8192,
            "messages": prompts
        }

        return request


if __name__ == "__main__":
    maas = MY_MaaS_2025_HTTP_CAN_USE()
    print(maas.invoke("""你的角色是：客服、客户对话核心问题提炼专家。
你的任务是：根据客服、客户对话，提炼出沟通的核心问题，并反馈问题描述。
根据以上要求，我的输入是：

客户：南美东跌的不行
客户：cma1200了
客服：嗯，4月南美东跌价了
客户：这一水呢
客户：赶紧争取
客服：这一水已经结束了
客户：我反正1300给你
客服：我真的要亏的
"""))
